package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.modular.dto.ProxyUserDTO;
import cn.stylefeng.guns.modular.system.entity.UserInfoRes;
import cn.stylefeng.guns.modular.system.enums.ResultEnum;
import cn.stylefeng.guns.modular.system.exception.ProjectException;
import cn.stylefeng.guns.modular.system.service.ProxyUserService;
import cn.stylefeng.guns.modular.system.utils.ResultVOUtil;
import cn.stylefeng.guns.modular.system.vo.ResultVO;
import cn.stylefeng.guns.modular.system.vo.SubagentVO;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.modular.system.entity.User;

import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName 代理类
 * @Author lzy
 * @Date 2020/1/6 11:14
 * @VERSION 1.0
 **/
@Controller
@RequestMapping("/proxy")
public class ProxyUserController {
    private final static Logger log = LoggerFactory.getLogger(ProxyUserController.class);

//    private static final Integer PAGESIZE = 10;
    private static final String SECCESS = "SECCESS";

    private String PREFIX = "/modular/system/proxyUser/";

    @Autowired
    private ProxyUserService proxyUserService;


    /**
     * 跳转到主页面
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "proxyUser.html";
    }

    /**
     * 跳转添加页面
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "proxyUser_add.html";
    }

    /**
     * 跳转修改详情
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/editDetails")
    public String editDetails() {
        return PREFIX + "proxyUser_edit_details.html";
    }

    /**
     * 跳转修改费率
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/editRate")
    public String editRate() {
        return PREFIX + "proxyUser_edit_rate.html";
    }

    /**
     * 代理创建子代理
     * @return
     */
    @PostMapping("/createSubagent")
    @ResponseBody
    public ResultVO createSubagent(SubagentVO subagentVO){
        Long superiorAgentId = LoginContextHolder.getContext().getUserId();
        log.info("代理创建子代理-----邮箱：" +subagentVO.getEmail());
        log.info("代理创建子代理-----上级代理id：" +superiorAgentId);
        log.info("代理创建子代理-----手机号：" +subagentVO.getPhone());
        if (ObjectUtils.isEmpty(superiorAgentId)){
            throw new ProjectException(ResultEnum.USER_DOES_NOT_EXIST);
        }
        subagentVO.setSuperiorAgentId(superiorAgentId);
        Assert.isTrue(!ObjectUtils.isEmpty(subagentVO.getPhone()),ResultEnum.CODE_NOT_EXIST.getMessage());

        //TODO 判断账号(phone)是否重复
        Integer userCount = proxyUserService.getAccountCount(subagentVO.getPhone());
        if( userCount != 0){
            //该用户已经注册或在审批
            throw new RequestEmptyException(BizExceptionEnum.USER_ALREADY_REG.getMessage());
        }

        proxyUserService.insertProxyUser(subagentVO);
        return ResultVOUtil.success(SECCESS);
    }


    /**
     * 显示当前登录用户的所有列表(分页显示) 可以按照参数过滤
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param account   账号
     * @param name  名字
     * @return
     */
    @GetMapping("/selectMyProxy")
    @ResponseBody
    public ResultVO selectMyProxy(@RequestParam(value = "startTime", required = false) String startTime,
                                  @RequestParam(value = "endTime", required = false)String endTime,
                                  @RequestParam(value = "account", required = false)String account,
                                  @RequestParam(value = "name", required = false)String name,
                                  @RequestParam("page")Integer pageNum, @RequestParam("limit") Integer pageSize){
        Long id = LoginContextHolder.getContext().getUserId();
        log.info("查询id为：" +  id + " 代理的下级代理 " );
        Assert.isTrue(!ObjectUtils.isEmpty(id),ResultEnum.PROXYID_DOES_NOT_EXIST.getMessage());
        Assert.isTrue(!ObjectUtils.isEmpty(pageNum),ResultEnum.PLEASE_SET_PAGINATION_PARAMETERS.getMessage());
        //查询所有的子代理
        List<String> subUserIds = proxyUserService.findSubUserIdList(id.toString());

        //设置默认分页参数
        PageHelper.startPage(pageNum,pageSize);
        List<UserInfoRes> syss = proxyUserService.findListByCondition(startTime,endTime,account,name,subUserIds);
        PageInfo<UserInfoRes> pageInfo = new PageInfo<>(syss);
        return ResultVOUtil.success(pageInfo.getList(),pageInfo.getTotal());
    }

    /**
     * 代理详情
     * @return
     */
    @RequestMapping("/getProxyDetail")
    @ResponseBody
    public ResultVO selectProxy(@RequestParam("userId") Long id){
        Assert.isTrue(!ObjectUtils.isEmpty(id),ResultEnum.NO_MANDATORY_FIELDS.getMessage());
        User user = proxyUserService.selectProxy(id);
        return ResultVOUtil.success(user);
    }

    /**
     * 修改自己旗下的代理信息，不可以修改费率
     * @param subagentVO
     * @param id    需要修改的id
     * @return
     */
    @PostMapping("/updateProxy")
    @ResponseBody
    public ResultVO updateProxy(SubagentVO subagentVO,
                                @RequestParam("userId") Long id){
        //查询当前用户信息
        User user = proxyUserService.selectUserById(id);
        if(!ObjectUtils.isEmpty(subagentVO.getPhone())){
            //如果电话为空就使用user里面的电话,如果不为空的话就覆盖一下
            user.setPhone(subagentVO.getPhone());
        }
        if(!ObjectUtils.isEmpty(subagentVO.getEmail())){
            user.setEmail(subagentVO.getEmail());
        }
        ProxyUserDTO build = ProxyUserDTO.builder()
                .userId(id.toString())
                .account(subagentVO.getAccount())
                .email(subagentVO.getEmail())
                .name(subagentVO.getName())
                .phone(subagentVO.getPhone())
                .updateTime(new Date())
                .build();
        proxyUserService.updateProxy(build);
        return ResultVOUtil.success(SECCESS);
    }

    /**
     * 修改代理数据，不可以修改下级代理的密码，但是可以修改下级代理的费率（上级代理修改自己的下级代理费率）
     * @param exchangeRate 费率
     * superiorAgentId 修改人的id，拿来校验
     * @param userId 被修改人的id
     * @return
     */
    @PostMapping("/updateRate")
    @ResponseBody
    public ResultVO updateRate(@RequestParam("exchangeRate") BigDecimal exchangeRate,
                               @RequestParam("userId") Long userId) throws ProjectException {
        Long superiorAgentId = LoginContextHolder.getContext().getUserId();
        //当前代理
        User user = proxyUserService.selectUserById(superiorAgentId);
        //要修改的代理
        User rate = proxyUserService.selectUserById(userId);

        Assert.isTrue(!ObjectUtils.isEmpty(user),ResultEnum.PROXY_DOSE_NOT_EXIST.getMessage());
        Assert.isTrue(!ObjectUtils.isEmpty(rate),ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());

        //TODO 修改费率之后，如果当前代理下面的代理或者用户比修改之后的费率高，那么报错并且给出详细信息到前端
        //根据我的下级代理，找出下级代理的旗下代理们，一层就够
        List<User> proxyList = proxyUserService.selectProxyByUserId(userId.toString());
        if(proxyList.size() == 0){
            //如果该代理没有下级代理，那么仅仅不需要大于他的上级代理即可
            if(exchangeRate.compareTo(user.getExchangeRate()) != -1){
//                return ResultVOUtil.success("当前下级代理费率高于本代理且高于旗下代理");
                return ResultVOUtil.error(new ProjectException("当前修改代理不能高于当前代理"));
//                throw new ProjectException("当前修改代理不能高于当前代理");
            }
        }

        //TODO  还没测试，要去数据库加一些假数据
        for (User sysdlhtUser : proxyList) {
            //第一，修改我下级代理费率不能高于我，第二他的旗下代理不能高于他
            if (exchangeRate.compareTo(user.getExchangeRate()) != -1
                    && sysdlhtUser.getExchangeRate().compareTo(exchangeRate) != -1) {
                //如果旗下代理的费率大于本代理修改的费率，就直接报错给前端详细错误信息
//                throw new ProjectException("当前下级代理费率高于本代理且高于旗下代理");
                return ResultVOUtil.error(new ProjectException("当前下级代理费率高于本代理且高于旗下代理"));

            }
        }

        //判断是否有上下级关系
//        if (!rate.getSuperiorAgentId().equals(user.getUserId())){
//            throw new RequestEmptyException(ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());
//        }
        proxyUserService.updateRate(Long.valueOf(rate.getUserId()),exchangeRate);
        return ResultVOUtil.success(SECCESS);
    }

    /**
     * 删除代理
     * @return
     */
    @RequestMapping("/deleteProxy")
    @ResponseBody
    public ResultVO deleteProxy(@RequestParam("userId") Long userId){
        Long superiorAgentId = LoginContextHolder.getContext().getUserId();
        User user = proxyUserService.selectUserById(superiorAgentId);
        User rate = proxyUserService.selectUserById(userId);

        Assert.isTrue(!ObjectUtils.isEmpty(user),ResultEnum.PROXY_DOSE_NOT_EXIST.getMessage());
        Assert.isTrue(!ObjectUtils.isEmpty(rate),ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());
        //判断是否有上下级关系
//        if (rate.getSuperiorAgentId() != user.getUserId()){
//            throw new RequestEmptyException(ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());
//        }
        proxyUserService.deleteProxy(userId);
        return ResultVOUtil.success(SECCESS);
    }
}
